<template>
  <div class="container">
    <div class="row-wrapper">
      <div
        style="float: left; margin-top: 167px; margin-bottom: 108px;  height: 304px; width: 213px"
      ></div>

      <div class="login-form">
        <div class="left-content-qrcode">
          <img class="login-content-qrcode-img" src="../../assets/login_qrcode.png" />
          <p class="login-content-qrcode-title">栏宝APP</p>
        </div>
        <div class="left-content-bg">
          <img class="left-content-bg-img" src="../../assets/login_bg2.png" />
        </div>

        <div class="left-content-bg2">
          <img class="left-content-bg2-img" src="../../assets/login_title2.png" />
        </div>
        <div class="content-title1">
          <img class="content-title1-img" src="../../assets/login_title1.png" />
        </div>
        <div class="content-logo">
          <img class="content-logo-img" src="../../assets/login_logo.png" />
        </div>
        <div class="login-form-child">
          <p style="color: white;  font-size: 32px">用户登录</p>
          <a-form
            :label-col="{ span: 6 }"
            labelAlign="left"
            :wrapper-col="{ span: 12 }"
            id="formLogin"
            class="user-layout-login"
            ref="formLogin"
            :form="form"
            @submit="handleSubmit"
          >
            <a-form-item class="form-label-color-size" label="用户名：">
              <a-input
                type="text"
                placeholder="输入登录账号"
                v-decorator="[
                  'username',
                  {
                    rules: [
                      { required: true, message: '请输入登录账号！' },
                      { validator: handleUsernameOrEmail },
                    ],
                    validateTrigger: 'change',
                  },
                ]"
              >
                <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>

            <a-form-item class="form-label-color-size" label="密   码：">
              <a-input-password
                placeholder="输入登录密码"
                v-decorator="[
                  'password',
                  { rules: [{ required: true, message: '请输入登录密码！' }], validateTrigger: 'blur' },
                ]"
              >
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input-password>
            </a-form-item>

            <a-form-item>
              <a-button
                type="primary"
                htmlType="submit"
                :loading="state.loginBtn"
                :disabled="state.loginBtn"
                >登录</a-button
              >
              <a-checkbox
                style="margin-left: 10px; color: white"
                v-decorator="['rememberMe', { valuePropName: 'checked' }]"
                >记住密码</a-checkbox
              >
            </a-form-item>
          </a-form>

          <two-step-captcha
            v-if="requiredTwoStepCaptcha"
            :visible="stepCaptchaVisible"
            @success="stepCaptchaSuccess"
            @cancel="stepCaptchaCancel"
          ></two-step-captcha>
        </div>
      </div>
      <div class="login-form-bg"></div>
      <div
        style="float: right; margin-top: 167px; margin-bottom: 108px; height: 304px; width: 213px"
      ></div>
    </div>
  </div>
</template>

<script>
import md5 from 'md5'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getSmsCaptcha, get2step } from '@/api/login'

export default {
  components: {
    TwoStepCaptcha,
  },
  data() {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
      },
    }
  },
  created() {
    this.$store.commit('websoket/changeData',[{name:'isWebSoket',value:false},{name:'websoketData',value:{}}]);

  },
  // created() {
  //   get2step({})
  //     .then((res) => {
  //       this.requiredTwoStepCaptcha = res.result.stepCode
  //     })
  //     .catch(() => {
  //       this.requiredTwoStepCaptcha = false
  //     })
  //   this.requiredTwoStepCaptcha = true
  // },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login,
      } = this
      debugger

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          // loginParams[!state.loginType ? 'email' : 'username'] = values.username
          loginParams.phone = values.username
          loginParams.password = values.password
          // let _this = this;
          // this.$http.post('/auth/login',Object.assign({}, loginParams)).then(res => {
          //   if(res.code  == 0) {
          //     _this.loginSuccess(res)
          //     _this.$router.push({ path: '/' })
          //     // 延迟 1 秒显示欢迎信息
          //     setTimeout(() => {
          //       _this.$notification.success({
          //         message: '欢迎',
          //         description: `${timeFix()}，欢迎回来`,
          //       })
          //     }, 1000)
          //     _this.isLoginError = false
          //   }else{
          //     _this.isLoginError = true
          //     _this.$notification['error']({
          //       message: '错误',
          //       description: res.message,
          //       duration: 4,
          //     })
          //   }
          // }).finally(() => {
          //   state.loginBtn = false
          // })
          // loginParams.password = md5(values.password)
          Login(loginParams)
            .then((res) => this.loginSuccess(res))
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          getSmsCaptcha({ mobile: values.mobile })
            .then((res) => {
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8,
              })
            })
            .catch((err) => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess(res) {
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      // state.userInfo = {}
      this.$router.push({ path: '/' }, () =>{
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`,
        })
      })
      // 延迟 1 秒显示欢迎信息
      // setTimeout(() => {
      //   this.$notification.success({
      //     message: '欢迎',
      //     description: `${timeFix()}，欢迎回来`,
      //   })
      // }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: (err || {}).message || '请求出现错误，请稍后再试',
        duration: 4,
      })
    },
  },
  beforeDestroy() {
    this.$store.commit('websoket/changeData',{name:'isWebSoket',value:true})
  }
}
</script>

<style lang="less">
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
.login-container {
  width: 100%;
  height: auto;
}
.login-form {
  background: url(../../assets/login_main_bg.png);
  background-repeat: no-repeat;
  background-size: 1494px 579px;
  float: left;
  height: 579px;
  width: 1494px;
  position: fixed;
  left:50%;
  top:50%;
  transform:translate(-50%,-50%) ;
  z-index: 6;
}
.login-form-bg{
  position: fixed;
  top:168px;
  left: 0;

  width:100vw;
  height:302px;
  background: #163c8d;
}
.row-wrapper {
  height: auto;
  width: 100%;
  position: fixed;
  top: 50%;
  left: 50%;
  -webkit-transform: translateX(-50%) translateY(-50%);
}
.form-label-color-size .ant-form-item-label > label {
  color: #fff;
  font-size: 20px;
}
.login-form-child {
  float: left;
  margin-left: 114px;
  margin-top: 73px;
  width: 460px;
  height: auto;
}
.left-content-qrcode {
  float: left;
  width: 161px;
  margin-top: 205px;
  margin-bottom: 108px;
  margin-left: 46px;
}
.login-content-qrcode-img {
  width: 161px;
  height: 165px;
}
.login-content-qrcode-title {
  color: white;
  font-size: 37px;
  text-align: center;
}
.left-content-bg {
  float: left;
  width: 378px;
  margin-top: 168px;
  margin-bottom: 108px;
  margin-left: 48px;
}
.left-content-bg-img {
  width: 378.4px;
  height: 302.1px;
}
.left-content-bg2 {
  float: right;
  width: 252px;
  margin-top: 292px;
  margin-bottom: 108px;
  margin-right: 21px;
}
.left-content-bg2-img {
  width: 252px;
  height: 49px;
}
.content-title1 {
  float: right;
  width: 247px;
  margin-top: 75px;
  margin-right: -38px;
}
.content-title1-img {
  width: 247px;
  height: 48px;
}
.content-logo {
  float: right;
  width: 54px;
  margin-top: 74px;
  margin-right: 19px;
}
.content-logo-img {
  width: 54px;
  height: 54px;
}
</style>
